package com.njtoyo.taxi.admin.logic.business.simple_call;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.njtoyo.taxi.admin.mapper.master.entity.SimpleCallRideOrder;
import com.njtoyo.taxi.admin.mapper.master.enums.SimpleCallRideOrderPaymentChannel;
import com.njtoyo.taxi.admin.mapper.master.mapper.SimpleCallRideOrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SimpleCallRideOrderLogic {
    @Autowired
    private SimpleCallRideOrderMapper simpleCallRideOrderMapper;

    public List<SimpleCallRideOrder> selectByRideIds(Set<Long> rideIds) {
        return new LambdaQueryChainWrapper<>(simpleCallRideOrderMapper)
                .in(SimpleCallRideOrder::getRideId, rideIds)
                .list();
    }

    // 根据rideId获取一个rideOrder
    public SimpleCallRideOrder getOneRideOrderByRideId(Long rideId) {
        List<SimpleCallRideOrder> list = new LambdaQueryChainWrapper<>(simpleCallRideOrderMapper)
                .eq(SimpleCallRideOrder::getRideId, rideId)
                .orderByDesc(SimpleCallRideOrder::getId)
                .list();

        if (Objects.nonNull(list)) {
            Optional<SimpleCallRideOrder> first = list.stream().findFirst();
            if (first.isPresent()) {
                return first.get();
            }
        }

        return null;
    }

    public boolean onlineOrderSetOffline(Long rideId) {
        Date now = new Date();
        long ts = now.getTime() / 1000;

        return new LambdaUpdateChainWrapper<>(simpleCallRideOrderMapper)
                .eq(SimpleCallRideOrder::getRideId, rideId)
                .set(SimpleCallRideOrder::getIsOnline, false)
                .set(SimpleCallRideOrder::getIsPaid, true)
                .set(SimpleCallRideOrder::getPaymentChannel, SimpleCallRideOrderPaymentChannel.recharge)
                .set(SimpleCallRideOrder::getPaidTimestamp, Convert.toInt(ts))
                .set(SimpleCallRideOrder::getUpdatedAt, now)
                .update();
    }
}
